#include "client_manager.h"
#include <libwebsockets.h>
#include <stdlib.h>
#include <string.h>

// 初始化虚拟主机数据结构
void init_vhost_data(VHostData *vhd) {
    vhd->clients = NULL;
    vhd->client_count = 0;
    vhd->capacity = 0;
}

// 添加客户端到列表
void add_client(VHostData *vhd, Client *client) {
    // 检查是否需要扩容
    if (vhd->client_count >= vhd->capacity) {
        // 计算新容量（初始为8，之后翻倍）
        size_t new_capacity = (vhd->capacity == 0) ? 8 : vhd->capacity * 2;

        // 重新分配内存
        Client *new_clients = realloc(vhd->clients, new_capacity * sizeof(Client));
        if (!new_clients)
            return;

        vhd->clients = new_clients;
        vhd->capacity = new_capacity;
    }

    // 添加客户端并增加计数（值拷贝）
    vhd->clients[vhd->client_count] = *client;
    vhd->client_count++;
}

// 从列表中移除客户端
void remove_client(VHostData *vhd, struct lws *wsi) {
    // 遍历查找匹配的客户端
    for (int i = 0; i < vhd->client_count; i++) {
        if (vhd->clients[i].wsi == wsi) {
            // 将最后一个元素移动到当前位置（避免移动整个数组）
            if (i < vhd->client_count - 1) {
                vhd->clients[i] = vhd->clients[vhd->client_count - 1];
            }

            // 减少计数
            vhd->client_count--;

            // 如果数组太稀疏，缩小容量
            if (vhd->capacity > 16 && vhd->client_count < vhd->capacity / 4) {
                size_t new_capacity = vhd->capacity / 2;
                Client *new_clients = realloc(vhd->clients, new_capacity * sizeof(Client));
                if (new_clients) {
                    vhd->clients = new_clients;
                    vhd->capacity = new_capacity;
                }
            }

            break;
        }
    }
}

// 广播消息给所有客户端（除发送者外）
void broadcast_message(VHostData *vhd, const char *message, struct lws *sender) {
    size_t msg_len = strlen(message);

    // 分配缓冲区（LWS_PRE + 消息长度）
    unsigned char *buf = malloc(LWS_PRE + msg_len);
    if (!buf)
        return;

    // 复制消息内容
    memcpy(buf + LWS_PRE, message, msg_len);

    // 发送给所有客户端（除发送者外）
    for (int i = 0; i < vhd->client_count; i++) {
        if (vhd->clients[i].wsi != sender) {
            lws_write(vhd->clients[i].wsi, buf + LWS_PRE, msg_len, LWS_WRITE_TEXT);
        }
    }

    free(buf);
}

// client_manager.c
void update_client_in_vhd(VHostData *vhd, Client *client) {
    for (int i = 0; i < vhd->client_count; i++) {
        if (vhd->clients[i].wsi == client->wsi) {
            // 仅更新状态字段，保留其他数据
            vhd->clients[i].is_logged_in = client->is_logged_in;
            strncpy(vhd->clients[i].username, client->username, sizeof(vhd->clients[i].username));
            break;
        }
    }
}
// 获取登录用户数
int get_logged_in_count(VHostData *vhd) {
    int count = 0;
    for (int i = 0; i < vhd->client_count; i++) {
        if (vhd->clients[i].is_logged_in) {
            count++;
        }
    }
    return count;
}